<!-- eslint-disable prettier/prettier -->
<script setup lang="ts">
import { defineEmits, defineProps, ref, watch } from 'vue';

import { ElUploadFilled } from '@vben/icons';

import { StorageManager } from '@vben-core/shared/cache';

import {
  ElDialog,
  ElIcon,
  ElMessage,
  ElNotification,
  ElUpload,
} from 'element-plus';

import { fileApi, fileUploaderApi, publicResourcesApi } from '#/api';
import { $t } from '#/locales';
import { useCatalogStore } from '#/store';
import { uploadUtil } from '#/utils';

// 父组件控制显隐
const props = defineProps({
  modelValue: Boolean, // 用于 v-model 绑定
  uploadType: {
    type: String,
    default: 'personal', // 默认是个人空间
  },
});
const emit = defineEmits(['update:modelValue', 'uploadSuccess']);
const storageManager = new StorageManager({
  prefix: '',
  storageType: 'sessionStorage',
});
const rootCatalog = storageManager.getItem('rootCatalog') as string;
const userId = storageManager.getItem('userId') as string;
const catalogStore = useCatalogStore();
// 控制对话框显示
const visible = ref(props.modelValue);
watch(
  () => props.modelValue,
  (newVal) => {
    visible.value = newVal;
  },
);
// 关闭弹窗
const closeDialog = () => {
  visible.value = false;
  emit('update:modelValue', false);
};

// 处理上传请求
const handleHttpRequest = async (options) => {
  const file = options.file;
  const task = await uploadUtil.getTaskInfo(file);
  if (task) {
    const { finished, taskRecord } = task;
    const { fileIdentifier: identifier, id: taskId } = taskRecord;

    // 根据上传类型确定目录和 API
    const isPersonal = props.uploadType === 'personal';
    const catalog = isPersonal
      ? (catalogStore.currentCatalogId === '' &&
        catalogStore.rootCatalog === null
        ? (rootCatalog as string)
        : catalogStore.breadcrumb[catalogStore.breadcrumb.length - 1].catalogId)
      : 'null';

    const uploadApi = isPersonal
      ? fileApi.uploadFile
      : publicResourcesApi.uploadFile;

    if (finished) {
      try {
        await uploadApi(userId as string, taskId, catalog);
        emit('uploadSuccess'); // 通知父组件上传成功
        ElMessage.success($t('page.resources.fileUploadSuccessMessage'));
        closeDialog();
      } catch (error) {
        console.error(error);
        closeDialog();
      }
    } else {
      const errorList = await uploadUtil.handleUpload(
        file,
        taskRecord,
        options,
      );
      if (errorList.length > 0) {
        ElNotification.error({
          title: $t('page.resources.fileUploadErrorTitle'),
          message: $t('page.resources.fileUploadPartialFailureMessage'),
        });
        return;
      }
      await fileUploaderApi.merge(identifier);
      try {
        await uploadApi(userId as string, taskId, catalog);
        emit('uploadSuccess'); // 通知父组件上传成功
        ElMessage.success($t('page.resources.fileUploadSuccessMessage'));
        closeDialog();
      } catch (error) {
        console.error(error);
      }
    }
  } else {
    ElNotification.error({
      title: $t('page.resources.fileUploadErrorTitle'),
      message: $t('page.resources.fileUploadTaskFailureMessage'),
    });
  }
};

// 处理文件移除
const handleRemoveFile = (uploadFile) => {
  uploadUtil.handleRemoveFile(uploadFile);
};
</script>

<template>
  <ElDialog
    v-model="visible"
    v-if="visible"
    class="w-[30vw] max-w-[500px] rounded-2xl"
    align-center
    draggable
    @closed="closeDialog"
  >
    <template #header>
      <h4
        class="border-b border-gray-200 px-4 py-2 text-lg font-semibold text-gray-800"
      >
        {{ $t('page.resources.uploadFile') }}
      </h4>
    </template>

    <div class="m-6">
      <ElUpload
        drag
        action="/"
        multiple
        :http-request="handleHttpRequest"
        :on-remove="handleRemoveFile"
        class="w-full rounded-lg transition-colors duration-200 hover:bg-gray-100"
      >
        <div
          class="flex h-full w-full flex-col items-center justify-center p-8"
        >
          <ElIcon class="mb-4 text-4xl text-blue-500">
            <ElUploadFilled />
          </ElIcon>
          <div
            class="w-full text-center text-sm text-gray-600"
            v-html="$t('page.resources.uploadComponentText')"
          ></div>
        </div>
      </ElUpload>
    </div>
  </ElDialog>
</template>
